package zack.gateway.center.interfaces;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zack.gateway.center.application.ILoadBalancingService;
import zack.gateway.center.domain.docker.model.aggregates.NginxConfig;
import zack.gateway.center.domain.docker.model.vo.LocationVO;
import zack.gateway.center.domain.docker.model.vo.UpstreamVO;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.mysql.cj.conf.PropertyKey.logger;

/**
 * @author A1793
 */
@RestController
@RequestMapping("/wg/admin/load")
public class LoadBalancingMange {

    private Logger logger = LoggerFactory.getLogger(GatewayConfigManage.class);

    @Resource
    ILoadBalancingService loadBalancingService;

    public void copy() throws IOException {
        ProcessBuilder pb = new ProcessBuilder("docker",
                "cp",
                "/nginx.conf",
                "host:/mnt/c/javaData/git_test/my-api-gateway-center/docs/data/nginx/nginx.conf");
        pb.start();
    }

    @GetMapping(value = "updateNginxConfig", produces = "application/json;charset=utf-8")
    public void updateNginxConfig() {
        List<UpstreamVO> upstreamList = new ArrayList<>();

        upstreamList.add(new UpstreamVO("api01", "least_conn;",
                Arrays.asList("10.114.109.46:9001;", "10.114.109.46:9002;")));

        upstreamList.add(new UpstreamVO("api02", "least_conn;",
                Arrays.asList("10.114.109.46:9003;")));

        List<LocationVO> locationList = new ArrayList<>();
        locationList.add(new LocationVO("/api01/", "http://api01;"));
        locationList.add(new LocationVO("/api02/", "http://api02;"));

        NginxConfig nginxConfig = new NginxConfig(upstreamList, locationList);
        try {
            logger.info("刷新Nginx配置文件开始 nginxConfig：{}", JSON.toJSONString(nginxConfig));
            loadBalancingService.updateNginxConfig(nginxConfig);
            logger.info("刷新Nginx配置文件完成");
        } catch (Exception e) {
            logger.error("刷新Nginx配置文件失败", e);
        }
    }

}
